package music.play.util;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jfinal.json.Json;
import com.jfinal.log.Log;
import music.play.config.Constant;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;


public class JschUtil {


    private static final Log log = Log.getLog(JschUtil.class);

    private static Session session = createConnection();

    private JschUtil() {
    }

    public static String GetConnectionInfo() {
        if (null == session) {
            return "未连接.";
        } else {
            return "已连接到" + session.getHost();
        }
    }

    /**
     * 新线程执行命令
     */
    public static void ExecCommandByThread(String command) {
        new Thread(() -> ExecCommand(command)).start();
    }

    /**
     * 执行命令
     */
    public static String ExecCommand(String command) {
        Map<String, Object> resultMap = new HashMap<String, Object>() {{
            put("Command", command);
        }};

        ChannelExec channelExec = null;
        try {
            channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand(command);
            channelExec.setInputStream(null);
            BufferedReader outReader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
            BufferedReader errReader = new BufferedReader(new InputStreamReader(channelExec.getErrStream()));
            channelExec.connect();

            List<String> okList = new ArrayList<>();
            List<String> noList = new ArrayList<>();

            //读取执行结果
            String line;
            while ((line = outReader.readLine()) != null) {
                okList.add(line);
            }
            outReader.close();
            //读取错误结果
            while ((line = errReader.readLine()) != null) {
                noList.add(line);
            }
            errReader.close();
            resultMap.put("OutMsg", okList);
            resultMap.put("ErrMsg", noList);
        } catch (Exception e) {
            log.error("执行:" + command + "命令异常:" + e.getMessage());
            resultMap.put("ErrMsg", e.getMessage());
            e.printStackTrace();
        } finally {
            if (null != channelExec) {
                try {
                    channelExec.disconnect();
                } catch (Exception e) {
                    log.error("关闭channelExec通道发生异常:" + e.getMessage());
                }
            }
        }
        log.info(Json.getJson().toJson(resultMap));
        return Json.getJson().toJson(resultMap);
    }


    //创建服务器连接
    private static Session createConnection() {
        try {
            JSch jsch = new JSch();
            //根据用户名，密码，端口号获取session
            Session session = jsch.getSession(Constant.SshUser, Constant.SshHost, Constant.SshPort);
            session.setPassword(Constant.SshPass);

            //修改服务器/etc/ssh/sshd_config 中 GSSAPIAuthentication的值yes为no，解决用户不能远程登录
            session.setConfig("userauth.gssapi-with-mic", "no");

            //为session对象设置properties,第一次访问服务器时不用输入yes
            session.setConfig("StrictHostKeyChecking", "no");

            // 设置心跳间隔和次数(樹莓派上測試不用心跳也可以不斷)
            //session.setServerAliveInterval(60); // 每隔60秒发送心跳
            //session.setServerAliveCountMax(3); // 如果60秒内没有响应，则发送3次心跳后断开连接

            session.connect();

            log.warn("打开与服务器的会话:{}", Constant.SshHost);
            return session;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}